package com.pine.dbant.plugin.mysql.function;

import com.pine.dbant.common.jdbc.JdbcUtils;
import com.pine.dbant.common.model.JdbcMetadataTreeView;
import com.pine.dbant.common.plugin.meta.*;
import com.pine.sunflower.core.utils.Strings;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author xiaoyuan
 * @create 2023/3/20 14:43
 **/
public class MysqlCatalogFunction extends AbstractQueryMetadataFunction<JdbcMetadataAnalysisConfig, List> {

    public MysqlCatalogFunction(String type) {
        super(type);
    }

    @Override
    public List<MetadataNode> doQuery(JdbcMetadataAnalysisConfig metadataAnalysisConfig, QueryMetadataParam queryMetadataParam) {
        String sql = Strings.format(" select schema_name,default_character_set_name,default_collation_name " +
                "from information_schema.schemata ");
        List<Map<String, Object>> result = JdbcUtils.getSqlRunner(metadataAnalysisConfig.getConnection()).queryList(sql);
        List<MetadataNode> metadataNodes = new ArrayList<>();
        metadataNodes.addAll(result.stream()
                .map(map -> {
                            String dbName = String.valueOf(map.get("SCHEMA_NAME"));
                            return new DefaultMetadataNode().setName(dbName)
                                    .setId(Strings.format("{}_{}", metadataAnalysisConfig.getConnectionInfo().getId(), dbName))
                                    .setType(JdbcMetadataTreeView.CATALOG.getType())
//                        .setParentId(String.valueOf(metadataAnalysisConfig.getConnectionInfo().getId()))
                                    .addProperty(CONN_ID, metadataAnalysisConfig.getConnectionInfo().getId())
                                    .addProperty(CATALOG, dbName)
                                    .addProperties(map);

                        }
                ).collect(Collectors.toList()));
        return metadataNodes;
    }
}
